package com.youxin.busfoundation.config;

import java.net.InetAddress;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import com.youxin.foundation.utils.HostUtils;

import redis.clients.jedis.HostAndPort;

/**
 * ES加载配置类
 * @author yingde.cao
 *
 */
@Configuration
@PropertySource("classpath:${spring.profiles.active}/es.properties")
@ConfigurationProperties(prefix="es")
public class EsConfig {
	private String hosts;
	private String clustername;
	private String companyname,resourcename,contactname,companyent;
	
	public String getCompanyname() {
		return companyname;
	}

	public void setCompanyname(String companyname) {
		this.companyname = companyname;
	}

	public String getClustername() {
		return clustername;
	}

	public void setClustername(String clustername) {
		this.clustername = clustername;
	}

	public String getResourcename() {
		return resourcename;
	}

	public void setResourcename(String resourcename) {
		this.resourcename = resourcename;
	}

	public String getContactname() {
		return contactname;
	}

	public void setContactname(String contactname) {
		this.contactname = contactname;
	}


	private TransportAddress[] transportAddresses;

	public String getHosts() {
		return hosts;
	}

	public void setHosts(String hosts) {
		this.hosts = hosts;
	}

	private static EsConfig config;
	private static Object lockObj=new Object();

	/**
	 * 程序启动时加载Kafka的配置
	 * @param kafkaConfig
	 */
	public static void initConfig(EsConfig esConfig)
	{
		synchronized (lockObj) {
			if(config==null)
			{
				config=esConfig;
			}
		}
	}
	
	/**
	 * 取Kafka配置
	 * @return
	 */
	public static EsConfig getConfig()
	{
		return config;
	}
	
	public TransportAddress[] getHostAndPorts() throws Exception{
		if(transportAddresses!=null)
		{
			return transportAddresses;
		}
		Set<HostAndPort> hostAndPorts=HostUtils.parserHosts(hosts);
		
		List<TransportAddress> addresses=new ArrayList<>(hostAndPorts.size());
		for(HostAndPort item:hostAndPorts)
		{
			addresses.add(new InetSocketTransportAddress(InetAddress.getByName(item.getHost()), item.getPort()));
		}
		transportAddresses=addresses.toArray(new InetSocketTransportAddress[]{});	
		return transportAddresses;
	}

	public String getCompanyent() {
		return companyent;
	}

	public void setCompanyent(String companyent) {
		this.companyent = companyent;
	}

	public String[] getCompanyEntArray(){
		return companyent.split(",", -1);
	}
	
}
